<!--
  ${table.comment!(table.entityName!'')} - 管理页面
  
  功能描述: 
  - 数据查询: 支持多字段条件查询和分页
  - 数据展示: 使用SystemTable自定义表格组件
  - 数据操作: 新增、编辑、删除、批量删除
  - 导入导出: 支持Excel数据导入导出
  
  数据表: ${table.tableName!''}
  模块: ${table.moduleName!''}
  权限前缀: ${permissionPrefix!''}
  
  生成时间: ${now?string('yyyy-MM-dd HH:mm:ss')}
  作者: ${user.name!"系统"}
-->
<template>
  <div class="app-container p-6">
    <!-- 页面标题和操作按钮 - 完全匹配原型 -->
    <div class="page-header-section flex flex-col md:flex-row md:items-center md:justify-between mb-6">
      <div class="page-title-area">
        <h1 class="text-2xl font-bold text-text-primary">${table.comment!(table.entityName!'')}</h1>
        <p class="text-text-muted mt-2">管理${table.comment!(table.entityName!'')}数据，包括查询、新增、编辑、删除和批量操作</p>
      </div>
      <div class="page-actions-area mt-4 md:mt-0">
        <!-- 主要操作按钮 -->
        <button
          @click="handleAdd"
          v-permission="'${permissionPrefix}:add'"
          class="primary-action-btn bg-primary hover:bg-primary-hover text-white px-6 py-2 rounded-md flex items-center shadow-card transition-all"
        >
          <i class="fas fa-plus mr-2"></i>
          <span>新增${table.comment!(table.entityName!'')}</span>
        </button>
<#if table.templateType?has_content && table.templateType == 'multi'>

        <!-- 次要操作按钮 -->
        <button
          @click="handleAddWithRelations"
          v-permission="'${permissionPrefix}:add'"
          class="secondary-action-btn ml-2 px-4 py-2 border border-border rounded-md text-text-secondary hover:bg-bg-hover hover:text-text-primary transition-colors flex items-center text-sm"
        >
          <i class="fas fa-layer-group mr-2"></i>
          <span>新增(含关联)</span>
        </button>
</#if>
      </div>
    </div>

    <!-- 搜索和筛选区域 - 完全匹配原型样式 -->
    <div class="search-form-card bg-panel rounded-lg shadow-card p-6 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
<#list columns as c>
  <#-- 只为查询字段生成搜索控件 -->
  <#assign isQueryField = false>
  <#if c.queryBehavior?? || (c.isQueryCond?? && c.isQueryCond)>
    <#assign isQueryField = true>
  </#if>
  
  <#-- 跳过系统字段 -->
  <#assign skipField = false>
  <#if c.columnName?? && (c.columnName?lower_case == "tenant_id" || c.columnName?lower_case == "create_by" || c.columnName?lower_case == "create_time" || c.columnName?lower_case == "update_by" || c.columnName?lower_case == "update_time" || c.columnName?lower_case == "deleted" || c.columnName?lower_case == "version")>
    <#assign skipField = true>
  </#if>
  
  <#if isQueryField && !skipField>
    <#-- 判断查询类型 -->
    <#assign queryType = "eq">
    <#if c.queryBehavior?? && c.queryBehavior?is_string>
      <#assign queryType = c.queryBehavior?lower_case>
    <#elseif c.queryBehavior?? && c.queryBehavior.type??>
      <#assign queryType = c.queryBehavior.type?lower_case>
    <#elseif c.javaType?? && (c.javaType?contains("String") || c.javaType == "String")>
      <#-- String类型默认模糊查询 -->
      <#if c.propertyName?lower_case?ends_with("code") || c.propertyName?lower_case?ends_with("no") || c.propertyName?lower_case?ends_with("id")>
        <#assign queryType = "eq">
      <#else>
        <#assign queryType = "like">
      </#if>
    <#elseif c.javaType?? && (c.javaType?contains("Date") || c.javaType?contains("LocalDateTime") || c.javaType?contains("LocalDate"))>
      <#assign queryType = "between">
    </#if>
    
        <!-- ${c.comment!(c.propertyName!'')}搜索 -->
        <div>
          <label class="block text-text-secondary mb-2 text-sm font-medium">${c.comment!(c.propertyName!'')}</label>
    <#if queryType == "between">
          <div class="search-date-wrapper">
            <el-date-picker
              v-model="dateRange.${c.propertyName}"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              class="w-full"
              @change="handleDateRangeChange('${c.propertyName}')"
            />
          </div>
    <#elseif c.dictCode?has_content>
          <div class="search-select-wrapper">
            <el-select
              v-model="queryParams.${c.propertyName}"
              placeholder="请选择${c.comment!(c.propertyName!'')}"
              clearable
              class="search-select w-full"
            >
              <el-option
                v-for="item in dict${c.propertyName?cap_first}Options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
    <#elseif (c.uiComponent!"input")?lower_case == "select">
          <div class="search-select-wrapper">
            <el-select
              v-model="queryParams.${c.propertyName}"
              placeholder="请选择${c.comment!(c.propertyName!'')}"
              clearable
              class="search-select w-full"
            >
              <!-- TODO: 根据实际业务配置选项 -->
              <el-option label="选项1" :value="1" />
              <el-option label="选项2" :value="2" />
            </el-select>
          </div>
    <#else>
          <div class="relative">
            <input
              type="text"
              v-model="queryParams.${c.propertyName}"
              placeholder="请输入${c.comment!(c.propertyName!'')}"
              class="search-input pl-10 pr-4 py-2 w-full rounded-md border border-border bg-bg-hover focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
            >
            <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-muted"></i>
          </div>
    </#if>
        </div>
  </#if>
</#list>
      </div>

      <!-- 高级搜索和操作按钮 -->
      <div class="mt-4 flex justify-between items-center">
        <button class="text-primary hover:text-primary-hover text-sm transition-colors">
          <i class="fas fa-sliders-h mr-1"></i>
          高级搜索
        </button>

        <!-- 操作按钮组 -->
        <div class="flex space-x-3">
          <button
            @click="resetQuery"
            class="px-4 py-2 border border-border rounded-md text-text-secondary hover:bg-bg-hover transition-colors"
          >
            重置
          </button>
          <button
            @click="handleQuery"
            class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-hover shadow-sm transition-colors"
          >
            搜索
          </button>
        </div>
      </div>
    </div>

    <!-- 批量操作工具栏 -->
    <div v-if="selectedIds.length > 0" class="batch-actions-bar bg-panel rounded-lg shadow-card p-4 mb-4 flex justify-between items-center">
      <div class="flex items-center">
        <span class="text-primary font-medium mr-4">已选择 {{ selectedIds.length }} 项</span>
        <button
          @click="handleBatchDelete"
          v-permission="'${permissionPrefix}:remove'"
          class="px-4 py-2 bg-danger hover:bg-danger-hover text-white rounded-md transition-colors flex items-center"
        >
          <i class="fas fa-trash mr-2"></i>
          <span>批量删除</span>
        </button>
      </div>
      <button
        @click="clearSelection"
        class="px-3 py-1 border border-border rounded-md text-text-secondary hover:bg-bg-hover transition-colors"
      >
        取消选择
      </button>
    </div>

    <!-- 数据表格区域 - 使用SystemTable自定义组件 -->
    <SystemTable
      ref="tableRef"
      :title="'${table.comment!(table.entityName!'')}列表'"
      :data="tableData"
      :total="total"
      v-loading="loading"
      row-key="id"
      @page-change="handlePageChange"
      @selection-change="handleSelectionChange"
      @export="handleExport"
      @import="handleImportClick"
      export-permission="${permissionPrefix}:export"
      import-permission="${permissionPrefix}:import"
    >
      <!-- 复选框列 -->
      <el-table-column type="selection" width="55" align="center" />
      
      <!-- ID列 -->
      <el-table-column prop="id" label="ID" width="80" align="center" show-overflow-tooltip />
      
      <!-- 业务字段列 -->
<#list columns as c>
  <#-- 判断是否显示在列表 -->
  <#assign showInList = false>
  <#if c.isListCol?? && c.isListCol>
    <#assign showInList = true>
  <#elseif !(c.isListCol??)>
    <#-- 如果没有配置isListCol，默认显示非系统字段 -->
    <#assign showInList = true>
  </#if>
  
  <#-- 跳过系统字段和主键 -->
  <#assign skipField = false>
  <#if c.columnName?? && (c.columnName?lower_case == "tenant_id" || c.columnName?lower_case == "create_by" || c.columnName?lower_case == "update_by" || c.columnName?lower_case == "deleted" || c.columnName?lower_case == "version")>
    <#assign skipField = true>
  </#if>
  <#if (c.isPk?? && c.isPk) || (c.propertyName?? && c.propertyName?lower_case == "id")>
    <#assign skipField = true>
  </#if>
  
  <#if showInList && !skipField>
      <el-table-column 
        prop="${c.propertyName}" 
        label="${c.comment!(c.propertyName!'')}" 
    <#if c.javaType?? && (c.javaType?contains("String") || c.javaType == "String")>
        min-width="120"
    <#elseif c.javaType?? && (c.javaType?contains("Date") || c.javaType?contains("LocalDateTime"))>
        width="180"
    <#else>
        width="100"
    </#if>
        show-overflow-tooltip
    <#if c.dictCode?has_content>
      >
        <template #default="{ row }">
          <el-tag v-if="row.${c.propertyName} !== null && row.${c.propertyName} !== undefined" type="info" size="small">
            {{ get${c.propertyName?cap_first}Label(row.${c.propertyName}) }}
          </el-tag>
          <span v-else class="text-text-muted">-</span>
        </template>
      </el-table-column>
    <#elseif c.propertyName?lower_case?contains("status") || c.propertyName?lower_case?contains("enabled")>
      >
        <template #default="{ row }">
          <el-tag :type="row.${c.propertyName} ? 'success' : 'danger'" size="small">
            {{ row.${c.propertyName} ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
    <#else>
      />
    </#if>
  </#if>
</#list>
      
      <!-- 时间字段列 -->
<#list columns as c>
  <#if c.columnName?? && (c.columnName?lower_case == "create_time" || c.columnName?lower_case == "update_time")>
      <el-table-column 
        prop="${c.propertyName}" 
        label="${c.comment!(c.propertyName!'')}" 
        width="180"
        show-overflow-tooltip
      />
  </#if>
</#list>
      
      <!-- 操作列 -->
      <el-table-column label="操作" fixed="right" align="center" width="<#if table.templateType?has_content && table.templateType == 'multi'>200<#else>150</#if>">
        <template #default="{ row }">
          <div class="table-actions flex justify-center gap-2">
            <button
              @click="handleEdit(row)"
              v-permission="'${permissionPrefix}:edit'"
              class="action-btn edit-btn"
              title="编辑"
            >
              <i class="fas fa-edit"></i>
            </button>
<#if table.templateType?has_content && table.templateType == 'multi'>
            <button
              @click="handleEditWithRelations(row)"
              v-permission="'${permissionPrefix}:edit'"
              class="action-btn view-btn"
              title="编辑(含关联)"
            >
              <i class="fas fa-layer-group"></i>
            </button>
</#if>
            <button
              @click="handleDelete(row)"
              v-permission="'${permissionPrefix}:remove'"
              class="action-btn delete-btn"
              title="删除"
            >
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </template>
      </el-table-column>
    </SystemTable>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="dialog-form"
      >
<#list columns as c>
  <#-- 跳过系统字段 -->
  <#assign skipField = false>
  <#if c.columnName?? && (c.columnName?lower_case == "tenant_id" || c.columnName?lower_case == "create_by" || c.columnName?lower_case == "create_time" || c.columnName?lower_case == "update_by" || c.columnName?lower_case == "update_time" || c.columnName?lower_case == "deleted" || c.columnName?lower_case == "version")>
    <#assign skipField = true>
  </#if>
  
  <#-- 主键字段特殊处理：编辑时显示，新增时隐藏 -->
  <#if (c.isPk?? && c.isPk) || (c.propertyName?? && c.propertyName?lower_case == "id")>
        <el-form-item label="ID" v-if="formData.${c.propertyName}">
          <el-input v-model="formData.${c.propertyName}" disabled />
        </el-form-item>
  <#-- 业务字段：根据配置或默认规则显示 -->
  <#elseif !skipField && ((c.isFormField?? && c.isFormField) || !(c.isFormField??))>
        <el-form-item 
          label="${c.comment!(c.propertyName!'')}" 
          prop="${c.propertyName}"
        >
    <#if c.dictCode?has_content>
          <el-select
            v-model="formData.${c.propertyName}"
            placeholder="请选择${c.comment!(c.propertyName!'')}"
            clearable
            class="w-full"
          >
            <el-option
              v-for="item in dict${c.propertyName?cap_first}Options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
    <#elseif (c.uiComponent!"input")?lower_case == "select">
          <el-select
            v-model="formData.${c.propertyName}"
            placeholder="请选择${c.comment!(c.propertyName!'')}"
            clearable
            class="w-full"
          >
            <!-- TODO: 根据实际业务配置选项 -->
            <el-option label="选项1" :value="1" />
            <el-option label="选项2" :value="2" />
          </el-select>
    <#elseif (c.uiComponent!"input")?lower_case == "switch">
          <el-switch v-model="formData.${c.propertyName}" />
    <#elseif (c.uiComponent!"input")?lower_case == "number">
          <el-input-number v-model="formData.${c.propertyName}" :min="0" class="w-full" />
    <#elseif (c.uiComponent!"input")?lower_case == "textarea">
          <el-input
            v-model="formData.${c.propertyName}"
            type="textarea"
            :rows="3"
            placeholder="请输入${c.comment!(c.propertyName!'')}"
          />
    <#elseif c.javaType?? && (c.javaType?contains("Date") || c.javaType?contains("LocalDateTime"))>
          <el-date-picker
            v-model="formData.${c.propertyName}"
            type="datetime"
            placeholder="请选择${c.comment!(c.propertyName!'')}"
            class="w-full"
          />
    <#elseif c.javaType?? && c.javaType?contains("LocalDate")>
          <el-date-picker
            v-model="formData.${c.propertyName}"
            type="date"
            placeholder="请选择${c.comment!(c.propertyName!'')}"
            class="w-full"
          />
    <#else>
          <el-input
            v-model="formData.${c.propertyName}"
            placeholder="请输入${c.comment!(c.propertyName!'')}"
          />
    </#if>
        </el-form-item>
  </#if>
</#list>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

<#if table.templateType?has_content && table.templateType == 'multi'>
    <!-- 关联数据管理对话框 -->
    <el-dialog
      v-model="relationsDialogVisible"
      :title="relationsDialogTitle"
      width="900px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="基本信息" name="basic">
          <el-form
            :model="relationsFormData.entity"
            label-width="120px"
            class="dialog-form"
          >
            <!-- TODO: 配置主表单字段 -->
            <el-form-item label="ID" v-if="relationsFormData.entity.id">
              <el-input v-model="relationsFormData.entity.id" disabled />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
<#if table.ext?? && table.ext.relations??>
  <#list table.ext.relations as r>
        <!-- ${r.comment!'关联数据'} - ${r.alias} -->
        <el-tab-pane label="${r.comment!r.alias}" name="${r.alias}">
          <el-alert
            title="编辑${r.comment!r.alias}"
            type="info"
            :closable="false"
            class="mb-4"
          >
            请配置关联表 ${r.table} 的数据。TODO: 根据子表实际字段修改下方表单
          </el-alert>
          
          <el-button size="small" @click="addRelationRow_${r.alias}" class="mb-2">
            <i class="fas fa-plus mr-1"></i>
            新增一行
          </el-button>
          
          <el-table :data="relationsFormData.${r.alias}" border size="small">
            <!-- TODO: 根据子表 ${r.table} 的实际字段修改以下列 -->
            <el-table-column label="字段1" width="200">
              <template #default="{ row }">
                <el-input v-model="row.field1" placeholder="字段1" />
              </template>
            </el-table-column>
            <el-table-column label="字段2" width="200">
              <template #default="{ row }">
                <el-input v-model="row.field2" placeholder="字段2" />
              </template>
            </el-table-column>
            <el-table-column label="字段3" width="200">
              <template #default="{ row }">
                <el-input-number v-model="row.field3" placeholder="字段3" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center" fixed="right">
              <template #default="{ $index }">
                <el-button
                  size="small"
                  type="danger"
                  @click="removeRelationRow_${r.alias}($index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
  </#list>
<#else>
        <!-- TODO: 根据实际关联表配置 -->
        <el-tab-pane label="关联数据" name="relations">
          <el-alert
            title="提示"
            type="warning"
            :closable="false"
            class="mb-4"
          >
            请在代码生成配置中添加 table.ext.relations，或手动实现子表编辑功能
          </el-alert>
        </el-tab-pane>
</#if>
      </el-tabs>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="relationsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitWithRelations" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
</#if>

    <!-- 导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入${table.comment!table.entityName}"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="import-section">
        <el-alert
          title="导入说明"
          type="info"
          :closable="false"
          class="mb-4"
        >
          <ul class="list-disc list-inside text-sm">
            <li>请先下载模板，按照模板格式填写数据</li>
            <li>仅支持.xlsx格式文件，大小不超过10MB</li>
            <li>勾选"更新已存在数据"可覆盖现有数据</li>
          </ul>
        </el-alert>

        <div class="mb-4">
          <el-button @click="handleDownloadTemplate" class="w-full">
            <i class="fas fa-download mr-2"></i>
            下载导入模板
          </el-button>
        </div>

        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :on-change="handleFileChange"
          :limit="1"
          accept=".xlsx,.xls"
          drag
          class="upload-demo"
        >
          <div class="el-upload__text">
            <i class="fas fa-cloud-upload-alt text-4xl text-primary mb-2"></i>
            <div>将文件拖到此处，或<em>点击上传</em></div>
          </div>
        </el-upload>

        <div class="mt-4">
          <el-checkbox v-model="importOptions.updateSupport">
            更新已存在的数据
          </el-checkbox>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleImportConfirm"
            :loading="importLoading"
            :disabled="!importFile"
          >
            开始导入
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/**
 * ${table.comment!(table.entityName!'')} - 管理页面
 * 
 * 功能模块:
 * - 数据查询与展示
 * - 新增、编辑、删除操作
 * - 批量删除
 * - Excel导入导出
 * <#if table.templateType?has_content && table.templateType == 'multi'>
 * - 主从表关联数据管理
 * </#if>
 * 
 * @author ${user.name!"系统"}
 * @since ${now?string('yyyy-MM-dd HH:mm:ss')}
 */
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import SystemTable from '@/components/SystemTable/index.vue'

// 导入API - 使用统一的API对象和WithUI封装函数
import ${lowerEntity}Api, {
  export${table.entityName}WithUI,
  import${table.entityName}WithUI,
  download${table.entityName}TemplateWithUI
} from '@/api/${lowerEntity}'

// ==================== 数据状态 ====================
const loading = ref(false)
const submitLoading = ref(false)
const tableRef = ref()
const formRef = ref<FormInstance>()
const uploadRef = ref()

// 查询参数
const queryParams = reactive<any>({
  current: 1,
  size: 10
})

// 日期范围（用于时间范围查询）
const dateRange = reactive<Record<string, any>>({})

// 表格数据
const tableData = ref<any[]>([])
const total = ref(0)
const selectedIds = ref<any[]>([])

// ==================== 字典数据 ====================
<#list columns as c>
  <#if c.dictCode?has_content>
const dict${c.propertyName?cap_first}Options = ref<any[]>([
  // TODO: 从字典服务加载 ${c.dictCode}
])
  </#if>
</#list>

// ==================== 对话框状态 ====================
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = reactive<any>({})

// 表单验证规则
const formRules = reactive({
<#list columns as c>
  <#-- 跳过系统字段和主键 -->
  <#assign skipField = false>
  <#if c.columnName?? && (c.columnName?lower_case == "tenant_id" || c.columnName?lower_case == "create_by" || c.columnName?lower_case == "create_time" || c.columnName?lower_case == "update_by" || c.columnName?lower_case == "update_time" || c.columnName?lower_case == "deleted" || c.columnName?lower_case == "version")>
    <#assign skipField = true>
  </#if>
  <#if (c.isPk?? && c.isPk) || (c.propertyName?? && c.propertyName?lower_case == "id")>
    <#assign skipField = true>
  </#if>
  
  <#if !skipField && ((c.isFormField?? && c.isFormField) || !(c.isFormField??))>
    <#if c.isRequired?? && c.isRequired>
  ${c.propertyName}: [
    { required: true, message: '请输入${c.comment!(c.propertyName!'')}', trigger: 'blur' }
  ],
    </#if>
  </#if>
</#list>
})

<#if table.templateType?has_content && table.templateType == 'multi'>
// 关联数据对话框
const relationsDialogVisible = ref(false)
const relationsDialogTitle = ref('')
const activeTab = ref('basic')
const relationsFormData = reactive<any>({
  entity: {}<#if table.ext?? && table.ext.relations??>,
  <#list table.ext.relations as r>
  ${r.alias}: []<#if r_has_next>,</#if>
  </#list>
  </#if>
})
</#if>

// 导入对话框
const importDialogVisible = ref(false)
const importLoading = ref(false)
const importFile = ref<File | null>(null)
const importOptions = reactive({
  updateSupport: false
})

// ==================== 数据查询 ====================
const getList = async () => {
  loading.value = true
  try {
    const response = await ${lowerEntity}Api.list${table.entityName}(queryParams)
    tableData.value = response.data.records || []
    total.value = response.data.total || 0
  } catch (error) {
    ElMessage.error('查询失败')
    console.error('查询${table.comment!table.entityName}失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.current = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  Object.keys(queryParams).forEach(key => {
    if (key !== 'current' && key !== 'size') {
      delete queryParams[key]
    }
  })
  // 清空日期范围
  Object.keys(dateRange).forEach(key => {
    dateRange[key] = null
  })
  queryParams.current = 1
  getList()
}

// 日期范围变化处理
const handleDateRangeChange = (field: string) => {
  if (dateRange[field] && dateRange[field].length === 2) {
    queryParams[`${'${'}field}Start`] = dateRange[field][0]
    queryParams[`${'${'}field}End`] = dateRange[field][1]
  } else {
    delete queryParams[`${'${'}field}Start`]
    delete queryParams[`${'${'}field}End`]
  }
}

// 分页变化
const handlePageChange = (page: number, pageSize: number) => {
  queryParams.current = page
  queryParams.size = pageSize
  getList()
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 清除选择
const clearSelection = () => {
  tableRef.value?.clearSelection()
  selectedIds.value = []
}

// ==================== 新增编辑 ====================
const handleAdd = () => {
  dialogTitle.value = '新增${table.comment!table.entityName}'
  Object.keys(formData).forEach(key => delete formData[key])
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  dialogTitle.value = '编辑${table.comment!table.entityName}'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      if (formData.id) {
        await ${lowerEntity}Api.update${table.entityName}(formData.id, formData)
        ElMessage.success('更新成功')
      } else {
        await ${lowerEntity}Api.create${table.entityName}(formData)
        ElMessage.success('创建成功')
      }
      dialogVisible.value = false
      getList()
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}

<#if table.templateType?has_content && table.templateType == 'multi'>
// 关联数据管理
const handleAddWithRelations = () => {
  relationsDialogTitle.value = '新增${table.comment!table.entityName}(含关联数据)'
  Object.keys(relationsFormData.entity).forEach(key => delete relationsFormData.entity[key])
<#if table.ext?? && table.ext.relations??>
  <#list table.ext.relations as r>
  relationsFormData.${r.alias} = []
  </#list>
</#if>
  activeTab.value = 'basic'
  relationsDialogVisible.value = true
}

const handleEditWithRelations = async (row: any) => {
  relationsDialogTitle.value = '编辑${table.comment!table.entityName}(含关联数据)'
  
  // 查询详情（包含关联数据）
  try {
    const response = await ${lowerEntity}Api.get${table.entityName}(row.id)
    Object.assign(relationsFormData.entity, response.data)
<#if table.ext?? && table.ext.relations??>
  <#list table.ext.relations as r>
    relationsFormData.${r.alias} = response.data.${r.alias} || []
  </#list>
</#if>
  } catch (error) {
    console.error('查询详情失败:', error)
    ElMessage.error('查询详情失败')
    return
  }
  
  activeTab.value = 'basic'
  relationsDialogVisible.value = true
}

<#if table.ext?? && table.ext.relations??>
// 关联数据操作方法
  <#list table.ext.relations as r>
const addRelationRow_${r.alias} = () => {
  // TODO: 根据实际字段初始化对象
  relationsFormData.${r.alias}.push({ field1: '', field2: '', field3: 0 })
}

const removeRelationRow_${r.alias} = (index: number) => {
  relationsFormData.${r.alias}.splice(index, 1)
}

  </#list>
</#if>

const handleSubmitWithRelations = async () => {
  submitLoading.value = true
  try {
    const payload = {
      ...relationsFormData.entity<#if table.ext?? && table.ext.relations??>,
  <#list table.ext.relations as r>
      ${r.alias}: relationsFormData.${r.alias}<#if r_has_next>,</#if>
  </#list>
  </#if>
    }
    
    if (relationsFormData.entity.id) {
      await ${lowerEntity}Api.update${table.entityName}WithRelations(relationsFormData.entity.id, payload)
      ElMessage.success('更新成功')
    } else {
      await ${lowerEntity}Api.create${table.entityName}WithRelations(payload)
      ElMessage.success('创建成功')
    }
    relationsDialogVisible.value = false
    getList()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}
</#if>

// ==================== 删除操作 ====================
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除"${row.name || row.id}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await ${lowerEntity}Api.delete${table.entityName}(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${'${'}selectedIds.value.length} 条数据吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await ${lowerEntity}Api.batchDelete${table.entityName}(selectedIds.value)
    ElMessage.success(`成功删除 ${'${'}selectedIds.value.length} 条数据`)
    clearSelection()
    getList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
    }
  }
}

// ==================== 导入导出 ====================
const handleExport = async () => {
  await export${table.entityName}WithUI(queryParams)
}

const handleImportClick = () => {
  importFile.value = null
  importOptions.updateSupport = false
  importDialogVisible.value = true
}

const handleDownloadTemplate = async () => {
  await download${table.entityName}TemplateWithUI()
}

const handleFileChange = (file: any) => {
  importFile.value = file.raw
}

const handleImportConfirm = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }
  
  importLoading.value = true
  try {
    await import${table.entityName}WithUI(
      importFile.value,
      importOptions.updateSupport,
      () => {
        importDialogVisible.value = false
        getList()
      }
    )
  } finally {
    importLoading.value = false
  }
}

// ==================== 辅助函数 ====================
<#list columns as c>
  <#if c.dictCode?has_content>
// 获取${c.comment!c.propertyName}显示标签
const get${c.propertyName?cap_first}Label = (value: any) => {
  const item = dict${c.propertyName?cap_first}Options.value.find(opt => opt.value === value)
  return item?.label || value
}
  </#if>
</#list>

// ==================== 生命周期 ====================
onMounted(() => {
  getList()
  // TODO: 加载字典数据
})
</script>

<style lang="scss" scoped>
// 组件特定样式 - 继承全局样式，只定义特殊样式

.search-form-card {
  .search-input,
  .search-select {
    transition: all 0.3s ease;

    &:focus {
      box-shadow: 0 0 0 2px rgba(var(--primary-rgb), 0.2);
    }
  }
}

.table-actions {
  .action-btn {
    width: 32px;
    height: 32px;
    border-radius: 6px;
    border: 1px solid var(--border);
    background: var(--bg-panel);
    color: var(--text-secondary);
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background: var(--bg-hover);
      color: var(--text-primary);
    }

    &.edit-btn:hover {
      background: rgba(var(--primary-rgb), 0.1);
      color: var(--primary);
      border-color: var(--primary);
    }

    &.delete-btn:hover {
      background: rgba(var(--danger-rgb), 0.1);
      color: var(--danger);
      border-color: var(--danger);
    }

    &.view-btn:hover {
      background: rgba(var(--success-rgb), 0.1);
      color: var(--success);
      border-color: var(--success);
    }
  }
}

.dialog-form {
  :deep(.el-form-item) {
    margin-bottom: 22px;
  }
}

.import-section {
  :deep(.el-upload) {
    width: 100%;
  }

  :deep(.el-upload-dragger) {
    width: 100%;
  }
}
</style>

</style>
